package com.mzy.basics.serializable.jsontoolclass;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Ives
 * * @date 2021/11/22
 */
public class Jackson {
  /**
   * 将json字符串转换为Java对象
   */
  @Test
  public void test(){
    // 创建Jackson核心对象 ObjectMapper
    ObjectMapper objectMapper = new ObjectMapper();
    String json = "{\"createTime\":1621341922450,\"id\":1,\"name\":\"DT\"}";
    try {
      Person person = objectMapper.readValue(json, Person.class);
      System.out.println("java对象->>>"+person);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
  }

  /**
   * 将Java对象转换为JSON 字符串
   */
  @Test
  public void test2(){
    // 创建Jackson核心对象 ObjectMapper
    ObjectMapper objectMapper = new ObjectMapper();
    Person person = new Person(1,"DT",new Date());
    try {
      String json = objectMapper.writeValueAsString(person);
      System.out.println("json字符串->>>"+json);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
  }

  /**
   * 将Java字符串数组转为JSON数组
   */
  @Test
  public void test3() throws JsonProcessingException {
    // 将JSON数组转换为array对象
    ObjectMapper mapper = new ObjectMapper();
    String json = "[{\"id\":1,\"name\":\"张三\",\"createTime\":1622719597081}, {\"id\":2,\"name\":\"李四\",\"createTime\":1622719597081}]";
    // 方式1
    Person[] pp1 = mapper.readValue(json, Person[].class);
    for (Person person : pp1) {
      System.out.println(person);
    }
    // 方式2
    List<Person> ppl2 = Arrays.asList(mapper.readValue(json, Person[].class));
    ppl2.stream().forEach(System.out::println);
    // 方式3
    List<Person> pp3 = mapper.readValue(json, new TypeReference<List<Person>>() {});
    pp3.stream().forEach(System.out::println);
  }

  /**
   * 将JSON数组转为JSON 字符串
   */
  @Test
  public void test4() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    List<Person> personList = new ArrayList<>();
    personList.add(new Person(1,"DT",new Date()));
    personList.add(new Person(2,"DT1",new Date()));
    personList.add(new Person(3,"DT2",new Date()));
    String json = objectMapper.writeValueAsString(personList);
    System.out.println("json->>>"+json);
  }

  @Test
  public void test5(){
    Person person = new Person();
    System.out.println(person);
  }
}
